package io

import (
	"fmt"
	"strconv"
	"time"

	"go.bug.st/serial"
)

type COMMClient struct {
	serial.Port
	serial.Mode
	//io.ReadWriteCloser
	comName          string
	useAutoReconnect bool
	connecting       bool
	timeOutMilsecond int
}

func (_this *COMMClient) IsConnecting() bool {
	return _this.connecting
}

func (_this *COMMClient) AutoReconnect(async bool) {
	reconnectFunc := func() {
		if _this.connecting {
			return
		}
		_this.connecting = true
		for i := 0; _this.Connect() != nil; i++ {
			fmt.Println("重连中..." + strconv.Itoa(i))
			if i < 3 {
				time.Sleep(time.Second * 3)
			} else if i < 5 {
				time.Sleep(time.Second * 15)
			} else if i < 10 {
				time.Sleep(time.Second * 30)
			} else if i < 50 {
				time.Sleep(time.Second * 60)
			} else {
				time.Sleep(time.Second * 60 * 3)
			}
		}
		_this.connecting = false
	}
	if async {
		go reconnectFunc()
	} else {
		reconnectFunc()
	}

}

func (_this *COMMClient) Connect() error {
	if _this.useAutoReconnect {
		_this.AutoReconnect(false)
		return nil
	}
	if _this.Port != nil {
		_this.Port.Close()
	}
	var err error
	_this.Port, err = serial.Open(_this.comName, &_this.Mode)
	_this.Port.SetReadTimeout(time.Millisecond * time.Duration(_this.timeOutMilsecond))
	if err != nil {
		return err
	}
	return nil
}

func (_this *COMMClient) Read() ([]byte, error) {
	buffer := make([]byte, 4096)
	len, err := _this.Port.Read(buffer)
	if err != nil {
		if _this.useAutoReconnect {
			_this.AutoReconnect(false)
		}
		return nil, err
	}
	buffer = buffer[:len]
	return buffer, nil
}
func (_this *COMMClient) Write(buffer []byte) error {
	_, err := _this.Port.Write(buffer)
	if err != nil && _this.useAutoReconnect {
		_this.AutoReconnect(false)
	}
	return err
}
